package org.ishequ.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class MultiThreadDownloader {

	public static void main(String [] args){
		String path = "http://192.168.1.215:8080/web/QQ2010Beta.exe";
		int threadsize = 3;
		try {
			new MultiThreadDownloader().download(path, threadsize);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void download(String path, int threadsize) throws Exception {
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		if(conn.getResponseCode() == 200){
			int length = conn.getContentLength();
			File file = new File(getFileName(path));
			RandomAccessFile saveFile = new RandomAccessFile(file,"rwd");
			saveFile.setLength(length);
			saveFile.close();
			int block = length % threadsize == 0 ? length / threadsize : length / threadsize +1;
			for(int i=0;i<threadsize;i++){
				new DownloadThread(i,block,url,file).start();
			}
		}
	}
	
	private String getFileName(String path) {
		return path.substring(path.lastIndexOf("/")+1);
	}

	private final class DownloadThread extends Thread {
		
		private int threadid;
		private int block;
		private URL downloadUrl;
		private File file;
		
		public DownloadThread(int threadid, int block, URL downloadUrl,
				File file) {
			super();
			this.threadid = threadid;
			this.block = block;
			this.downloadUrl = downloadUrl;
			this.file = file;
		}



		public void run(){
			int startPos = threadid * block ;
			int endPos = (threadid + 1) * block - 1;
			try {
				RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
				accessFile.seek(startPos);
				HttpURLConnection conn = (HttpURLConnection) downloadUrl.openConnection();
				conn.setConnectTimeout(5000);
				conn.setRequestMethod("GET");
				conn.setRequestProperty("Range", "bytes="+ startPos+ "-"+ endPos);
				if(conn.getResponseCode() == 206){
					InputStream in = conn.getInputStream();
					byte[] buffer = new byte[1024];
					int len = 0;
					while((len = in.read(buffer)) != -1){
						accessFile.write(buffer,0,len);
					}
					accessFile.close();
					in.close();
					System.out.println("The "+threadid+" thread has download.");
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		
	}
	
	
}
